<template>
  <div class="page-content">
    <div class="header">
      <h3>短信设置</h3>
    </div>

    <div class="content">
      <el-form
        ref="ruleFormRef"
        style="max-width: 700px"
        :model="ruleForm"
        :rules="rules"
        label-width="auto"
      >
        <el-form-item label="厂商类型" prop="vendorType">
          <el-radio-group
            v-model="ruleForm.vendorType"
            :disabled="!isEdit"
            @change="changeVendorType"
          >
            <el-radio v-for="item in vendorTypeMap" :key="item.value" :value="item.value">{{
              item.name
            }}</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="Access Key" prop="accessKey">
          <el-input v-model="ruleForm.accessKey" clearable :disabled="!isEdit"></el-input>
        </el-form-item>
        <el-form-item label="Secret Key" prop="secretKey">
          <el-input v-model="ruleForm.secretKey" clearable :disabled="!isEdit"></el-input>
        </el-form-item>
        <el-form-item label="短信签名" prop="signature">
          <el-input v-model="ruleForm.signature" clearable :disabled="!isEdit"></el-input>
        </el-form-item>
        <el-form-item label="服务端点" prop="endpoint">
          <el-input v-model="ruleForm.endpoint" clearable :disabled="!isEdit"></el-input>
        </el-form-item>
        <el-form-item label="区域" prop="region">
          <el-input v-model="ruleForm.region" clearable :disabled="!isEdit"></el-input>
        </el-form-item>
        <el-form-item label="发送方ID" v-if="ruleForm.vendorType === '05'">
          <el-input v-model="ruleForm.senderId" clearable :disabled="!isEdit"></el-input>
        </el-form-item>
        <el-form-item label="应用ID" v-if="ruleForm.vendorType === '03'">
          <el-input v-model="ruleForm.appId" clearable :disabled="!isEdit"></el-input>
        </el-form-item>
        <el-form-item label="测试手机号">
          <el-input v-model="ruleForm.mobile" clearable :disabled="!isEdit"></el-input>
        </el-form-item>

        <div class="template-id"
          >短信模板ID <span class="tip">(请至少填写一种短信模板ID)</span></div
        >

        <el-form-item v-for="template in templateIdMap" :key="template.key" :label="template.label">
          <el-input
            v-model="ruleForm[template.key]"
            :disabled="!isEdit"
            class="template-input"
          ></el-input>
          <el-button type="primary" @click="handleTestTemplate(template)">测试</el-button>
        </el-form-item>

        <el-form-item label=" ">
          <el-button v-if="!isEdit" type="primary" size="large" @click="isEdit = true"
            >编辑</el-button
          >
          <el-button
            v-if="isEdit"
            type="primary"
            size="large"
            :loading="submitLoading"
            @click="submitForm(ruleFormRef)"
            >保存</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { smsSetting, updateSmsSetting, testSend } from '@/api/ApiList'
  import type { FormInstance, FormRules } from 'element-plus'

  type TemplateKey = 'userLogin' | 'userRegister' | 'userPassword' | 'changePassword'

  interface RuleForm {
    vendorType: string
    accessKey: string
    secretKey: string
    signature: string
    endpoint: string
    region: string
    appId?: string
    senderId?: string
    mobile?: string
    userLogin: string
    userRegister: string
    userPassword: string
    changePassword: string
    [key: string]: any
  }

  const vendorTypeMap: Record<string, any> = [
    { name: '阿里云', value: '01' },
    { name: '华为云', value: '02' },
    { name: '腾讯云', value: '03' },
    { name: '七牛云', value: '04' },
    { name: '极光短信', value: '05' },
    { name: '百度云', value: '06' }
  ]

  const templateIdMap: { key: TemplateKey; sendType: string; label: string }[] = [
    { key: 'userRegister', sendType: '1', label: '用户注册' },
    { key: 'userLogin', sendType: '2', label: '用户登录' },
    { key: 'userPassword', sendType: '3', label: '找回密码' },
    { key: 'changePassword', sendType: '4', label: '更换手机号' }
  ]

  const ruleFormRef = ref<FormInstance>()
  const ruleForm = reactive<RuleForm>({
    vendorType: '',
    accessKey: '',
    secretKey: '',
    signature: '',
    endpoint: '',
    region: '',
    appId: '',
    senderId: '',
    userLogin: '',
    userRegister: '',
    userPassword: '',
    changePassword: '',
    mobile: ''
  })

  const isEdit = ref(false)
  const submitLoading = ref(false)
  const configAllData = ref<any>([])

  const rules = reactive<FormRules<RuleForm>>({
    vendorType: [{ required: true, message: '请选择厂商类型', trigger: 'change' }],
    accessKey: [{ required: true, message: '请输入', trigger: 'blur' }],
    secretKey: [{ required: true, message: '请输入', trigger: 'blur' }],
    signature: [{ required: true, message: '请输入', trigger: 'blur' }]
  })

  const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid) => {
      if (valid) {
        if (checkSendType()) {
          handleEdit()
        }
      }
    })
  }

  function checkSendType() {
    const hasAtLeastOne = templateIdMap.some((item) => {
      return !!ruleForm[item.key]
    })

    if (!hasAtLeastOne) {
      ElMessage.warning('请至少填写一种店铺模板ID')
      return false
    }

    return true
  }

  function changeVendorType() {
    let obj = configAllData.value.find((item: any) => item.vendorType === ruleForm.vendorType)
    if (obj) {
      setFormData(obj)
    } else {
      ruleForm.accessKey = ''
      ruleForm.secretKey = ''
      ruleForm.signature = ''
      ruleForm.endpoint = ''
      ruleForm.region = ''
      ruleForm.appId = ''
      ruleForm.senderId = ''
      ruleForm.userLogin = ''
      ruleForm.userRegister = ''
      ruleForm.userPassword = ''
      ruleForm.changePassword = ''
      ruleForm.mobile = ''
    }
  }

  async function handleTestTemplate(template: {
    key: TemplateKey
    sendType: string
    label: string
  }) {
    if (!ruleForm.mobile) {
      return ElMessage.warning('请输入测试手机号')
    }

    if (!ruleForm[template.key]) {
      return ElMessage.warning('请输入短信模板ID')
    }

    const res = await testSend({
      mobile: ruleForm.mobile,
      sendType: template.sendType
    })
    if (res.code === '00000') {
      ElMessage.success('发送成功')
    } else {
      ElMessage.error(res.msg)
    }
  }

  async function handleEdit() {
    try {
      submitLoading.value = true

      const smsTypeList = templateIdMap
        .map((item) => ({
          sendType: item.sendType,
          templateId: ruleForm[item.key]
        }))
        .filter((item) => !!item.templateId)

      const res = await updateSmsSetting({
        vendorType: ruleForm.vendorType,
        accessKey: ruleForm.accessKey,
        secretKey: ruleForm.secretKey,
        signature: ruleForm.signature,
        endpoint: ruleForm.endpoint,
        region: ruleForm.region,
        appId: ruleForm.appId,
        senderId: ruleForm.senderId,
        mobile: ruleForm.mobile,
        smsTypeList,
        configName: '默认配置',
        isDefault: 1,
        status: 1
      })

      if (res.code === '00000') {
        ElMessage.success('编辑成功')
        isEdit.value = false
        await getData()
      } else {
        ElMessage.error(res.msg)
      }
    } catch {
    } finally {
      submitLoading.value = false
    }
  }

  async function getData() {
    try {
      const res = await smsSetting({
        pageNum: 1,
        pageSize: 10
      })
      if (res.code === '00000') {
        if (res.data.list && res.data.list.length > 0) {
          let obj = res.data.list.find((item: any) => item.isDefault === 1)
          setFormData(obj)

          configAllData.value = res.data.list
        }
      }
    } catch {
    } finally {
    }
  }

  function setFormData(data: any) {
    if (!data) return
    ruleForm.vendorType = data.vendorType
    ruleForm.accessKey = data.accessKey
    ruleForm.secretKey = data.secretKey
    ruleForm.signature = data.signature
    ruleForm.endpoint = data.endpoint
    ruleForm.region = data.region
    ruleForm.appId = data.appId
    ruleForm.senderId = data.senderId
    ruleForm.mobile = data.mobile

    templateIdMap.forEach((item) => {
      ruleForm[item.key] = ''
    })

    if (data.smsTypeList) {
      data.smsTypeList.forEach((item: any) => {
        const mapEntry = templateIdMap.find((m) => m.sendType === item.sendType)
        if (mapEntry) {
          ruleForm[mapEntry.key] = item.templateId
        }
      })
    }
  }

  onMounted(() => {
    getData()
  })
</script>

<style scoped lang="scss">
  .header {
    padding-bottom: 15px;
    border-bottom: 1px solid var(--art-border-color);
  }

  .content {
    margin-top: 20px;

    .template-id {
      margin-bottom: 20px;
      color: var(--art-text-gray-800);
      font-weight: bold;

      .tip {
        font-size: 12px;
        color: #999999;
      }
    }

    .template-input {
      width: 500px;
      margin-right: 40px;
    }
  }
</style>
